package com.livi.security.config.security;

import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;
import com.livi.security.model.commom.BaseResponse;
import com.livi.security.model.commom.ResultCode;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: 登录失败处理逻辑
 */
@Component
public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {

	@Override
	public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
			AuthenticationException e) throws IOException, ServletException {
		ResultCode resultCode = ResultCode.FAIL;
		if (e instanceof BadCredentialsException) {
			// 密码错误
			resultCode = ResultCode.ACCOUNT_ERROR;
		} else if (e instanceof CredentialsExpiredException) {
			// 密码过期
			resultCode = ResultCode.PASSWORD_EXPIRED;
		} else if (e instanceof DisabledException) {
			// 账号不可用
			resultCode = ResultCode.ACCOUNT_DISABLE;
		} else if (e instanceof LockedException) {
			// 账号锁定
			resultCode = ResultCode.ACCOUNT_LOCKED;
		} else if (e instanceof InternalAuthenticationServiceException) {
			// 用户不存在
			resultCode = ResultCode.ACCOUNT_ERROR;
		}
		// 返回json数据
		String res = JSONObject.toJSONString(new BaseResponse<>(false, resultCode));// 401，认证失败
		httpServletResponse.setContentType("text/json;charset=utf-8");
		httpServletResponse.getWriter().write(res);
	}
}
